﻿/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** FFmpegAudioSource.h
**
** -------------------------------------------------------------------------*/
// 是否支持ffmpeg功能

#pragma once

#include <iostream>
#include <thread>
#include <mutex>
#include <queue>
#include <cctype>
#include <stdio.h>
#include <string.h>
#include "pc/local_audio_source.h"
#include "ffmpeg_headers.h"

#include "AudioCapture.h"

typedef unsigned char uchar;
typedef unsigned int uint;


class FFmpegAudioSource : public AudioCapture, public MediaSourceEvent
{
public:
	FFmpegAudioSource(const std::string& uri, const std::map<std::string, std::string>& opts);
	~FFmpegAudioSource();
	virtual int Init(int nSampleRate, int nChannel, int nBitsPerSample) override;

	virtual int Init(const std::map<std::string, std::string>& opts) override;

	virtual int Start() override;

	virtual void Stop() override;

	virtual void Destroy() override;

	virtual void RegisterPcmCallback(PcmCallBack pcmCallback);

	virtual void RegisterAacCallback(AacCallBack aacCallBack);

	virtual bool onData(const char* id, unsigned char* buffer, ssize_t size, int64_t sourcets) { return true; };
	
virtual void HangUp() {};

	virtual void WakeUp() {};
public:
	
	virtual void OnSourceConnected(void* arg, const std::map<std::string, std::string>& opts)override;
	virtual void OnSourceDisConnected(int err) override;
	virtual bool onNewSession(const char* id, const char* media, const char* codec, const char* sdp, unsigned int rtpfrequency, unsigned int channels)override
	{
		return true;
	};

	virtual void OnSourceVideoPacket(const char* id, AVPacket* packet) override {};
	virtual void OnSourceAudioPacket(const char* id, AVPacket* packet)override;

	virtual void OnSourceVideoPacket(const char* id, uint8_t* aBytes, int aSize, int64_t ts,bool bKey) override;

	virtual void OnSourceAudioPacket(const char* id, uint8_t* aBytes, int aSize, int64_t t)override;
	virtual bool OnIsQuitCapture() {

		if (stopThread.load())
		{
		//	SPDLOG_LOGGER_ERROR(spdlogptr, "OnIsQuitCapture";
			return true;
		}
		return false;
	};

private:

	std::list<PcmCallBack> m_PcmCallbackList;

	std::mutex					m_mutex;                //互斥锁	
	AacCallBack				m_AACCallback;
	PcmCallBack m_pcmCallback;
	std::string				    m_audioourl;
	std::map<std::string, std::string> m_codec;
	MediaSourceAPI* m_pSource = nullptr;


	AudioResamplerAPI  *m_resampler=nullptr;
	FFmpegAudioDecoderAPI * m_audioDecder = nullptr;

	std::atomic<bool> stopThread;

	int m_nb_channels=2;

	int m_sample_rate=48000;
};
